package com.cskaoyan.demo1.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/7 9:49
 */

@WebServlet("/wx/storage/fetch/*")
public class WxStorageFetchServlet extends HttpServlet {
    String storagePath;

    @Override
    public void init() throws ServletException {
        storagePath = (String) getServletContext().getAttribute("storagePath");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取要读的东西
        // 1.获取uri
        String uri = req.getRequestURI();
        // 2.获取尾巴 ---- /*
        String fileName = uri.substring(uri.lastIndexOf("/"));
        // 读取文件 -- 写到浏览器
        File file = new File(storagePath,fileName);
        FileInputStream in = new FileInputStream(file);

        ServletOutputStream out = resp.getOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes,0,len);
        }

        in.close();


    }
}
